package com.atguigu.guli.service.edu.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.atguigu.guli.service.base.exception.GuliException;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.atguigu.guli.service.edu.entity.Subject;
import com.atguigu.guli.service.edu.entity.excel.SubjectExcelData;
import com.atguigu.guli.service.edu.listener.SubjectDataListener;
import com.atguigu.guli.service.edu.mapper.SubjectMapper;
import com.atguigu.guli.service.edu.service.SubjectService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 课程科目 服务实现类
 * </p>
 *
 * @author atguigu
 * @since 2021-06-24
 */
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {

    // 文件上传
    @Override
    public void importSubjects(MultipartFile file) {
        try {
            EasyExcel.read(file.getInputStream())  // 要读取的文件
                    .registerReadListener(new SubjectDataListener(baseMapper))  // 设置监听器
                    .head(SubjectExcelData.class)  // 如何解析生的对象
                    .excelType(ExcelTypeEnum.XLSX)  // 文件格式
                    .sheet(0)  // Excel中要读取的工作簿索引
                    .doRead();  // 开始读取
        } catch (Exception e) {

            log.error(ExceptionUtils.getStackTrace(e));//真正的异常信息
            throw new GuliException(ResultCodeEnum.EXCEL_DATA_IMPORT_ERROR);
            // e.printStackTrace();
        }

    }

    // 查询课程分类
    @Override
    public List<Subject> getSubjectsNestedList() {

        Map<String, Subject> maps = new HashMap<>();
        // 查询所有
        List<Subject> subjectsList = baseMapper.selectList(null);

        // 先查询并保存所有一级分类, 根据parent_id = 0
        for (Subject subject : subjectsList) {
            if ("0".equals(subject.getParentId())) {
                // 此时的 subject 为一级分类
                maps.put(subject.getId(), subject);
            }
        }

        // 根据一级分类的id等于二级分类的parent_id, 查询二级分类并将二级分类数据保存到一级分类中
        for (Subject subject : subjectsList) {
            if (!"0".equals(subject.getParentId())) {
                // 获取此二级分类的一级分类
                Subject OneSubject = maps.get(subject.getParentId());
                OneSubject.getChildren().add(subject);
            }
        }

        return new ArrayList<Subject>(maps.values());
    }
}
